import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import InvertButton from "./InvertButton";
import { useState, useMemo } from "react";
import { Checkbox } from "antd";
import { cloneDeep, find } from "lodash";
import Style from "./index.module.less";

const FieldCheckboxFormItem = props => {
	const { title, showList, onChange } = props;

	const [loading, setLoading] = useState(false);

	//全部展示
	const checkAllRender = useMemo(() => {
		if (showList.every(item => item.display == true)) {
			return true;
		} else {
			return false;
		}
	}, [showList]);

	//部分选择展示
	const indeterminateRender = useMemo(() => {
		if (showList.some(item => item.display == false) && !showList.every(item => item.display == false)) {
			return true;
		} else {
			return false;
		}
	}, [showList]);

	//点击全选
	const onCheckAllChange = e => {
		const val = e.target.checked;
		const arr = [...showList];
		if (val) {
			arr.map(v => (v.display = true));
		} else {
			arr.map(v => (v.display = false));
		}
		onChange(arr);
	};

	//点击反选
	const handReverseSelect = () => {
		const arr = [...showList];
		arr.map(v => (v.display = !v.display));
		onChange(arr);

	};

	//变更单个显示隐藏
	const changeDisplay = (e, r) => {
		const val = e.target.checked;
		const arr = cloneDeep(showList);
		const obj = find(arr, ["name", r.name]);
		if (obj) {
			obj.display = val;
		}
		onChange(arr);
	};

	return (
		<div>
			<div className={Style.header}>
				<SubTitle symbol as="s2" title={title} />
				<Checkbox
					indeterminate={indeterminateRender}
					checked={checkAllRender}
					onChange={onCheckAllChange}
					style={{ verticalAlign: "bottom" }}
				>
					全选
				</Checkbox>
				<InvertButton onClick={handReverseSelect} />
			</div>
			{showList.map(item => (
				<div className={Style.checkItem} key={item.name}>
					<Checkbox style={{ marginRight: "8px" }} checked={item.display} onChange={e => changeDisplay(e, item)} />
					{item.name}
				</div>
			))}
		</div>
	);
};

export default FieldCheckboxFormItem;
